<?php
namespace Cli\Controller;

use Cli\Controller\CommonController;
use Library\Wx;
//       /usr/local/php/bin/php /root/yyy/index.php Cli/Analysis/update
class AnalysisController extends CommonController {
	protected $card_model,
			$event_model,
			$device_model,
			$store_model,
			$real_users_model,
			$analysis_logs_model,
			$analysis_urls_model,
			$analysis_winning_model,
			$analysis_gather_model,
			$analysis_day_model,
			$analysis_activity_model,
			$analysis_materials_model,
			$analysis_equipment_model,
			$analysis_users_model,
			$wxpayorder_model;
	function _initialize() {
		parent::_initialize();
		$this->card_model= D("Card");
		$this->event_model= D("Events");
		$this->device_model = D("Device");
		$this->store_model = D("Store");
        $this->real_users_model = M("RealUsers");
		$this->analysis_logs_model= D("AnalysisLogs");
		$this->analysis_urls_model= D("AnalysisUrls");
		$this->analysis_winning_model= D("AnalysisWinning");
		$this->analysis_gather_model= D("AnalysisGather");
		$this->analysis_day_model= D("AnalysisDay");
		$this->analysis_activity_model= D("AnalysisActivity");
		$this->analysis_materials_model= D("AnalysisMaterials");
		$this->analysis_equipment_model= D("AnalysisEquipment");
		$this->analysis_users_model= D("AnalysisUsers");
        $this->wxpayorder_model = M("WxPayOrder");
		$this->prizes_order_model= D("PrizesOrder");
	}

    public function updatetx(){
    	set_time_limit(0);
		$logs = $this->logs();
		$urls = $this->urls();
		$users = $this->users();
		$materials = $this->materials();
		$winning = $this->winning();
		$update_users = $this->update_users();
        \Think\Log::record('update logs:'.$logs.' urls:'.$urls.' users: '.$users.' materials: '.$materials.' winning:'.$winning.' update_users:'.$update_users);
	}
    public function updatewx(){
    	set_time_limit(0);
		$day = $this->day();
		$activity = $this->activity();
		$equipment = $this->equipment();
		//根据微信数据计算活跃设备
		$indexwx = $this->index();
		$update_equipment = $this->update_equipment();
		//根据日志计算活跃设备
		$indextx = $this->index();
        \Think\Log::record('update  day:'.$day.' activity: '.$activity.' equipment: '.$equipment.' indexwx: '.$indexwx.' update_equipment: '.$update_equipment.' indextx: '.$indextx);
	}
	public function getArr( $file ){
        if(!file_exists( $file )){
            return false;//判断文件是否存在
        }
        $arr = file($file);
        $res = array();
        foreach($arr as $value){
            $value = trim( $value );
            if( empty($value)){
                continue;//去除空行
            }
			$res[] = $value;//确定第二维度
		}
        return $res;
   	}
	/*
INSERT INTO `yy_analysis_logs-16-09_bak`(`id`, `datetime`, `uuid`, `major`, `minor`, `pageid`, `openid`, `eid`, `etype`, `cid`, `ctype`, `moneys`, `cardnum`, `sn`)
SELECT yy_analysis_logs.`id`,
       yy_analysis_logs.`datetime`,
       yy_analysis_logs.`uuid`,
       yy_analysis_logs.`major`,
       yy_analysis_logs.`minor`,
       yy_analysis_logs.`pageid`,
       yy_analysis_logs.`openid`,
       yy_analysis_logs.`eid`,
       yy_analysis_logs.`etype`,
       yy_analysis_logs.`cid`,
       yy_analysis_logs.`ctype`,
       yy_analysis_logs.`moneys`,
       yy_analysis_logs.`cardnum`,
       yy_analysis_logs.`sn`
  FROM `yy_analysis_logs`
 WHERE date(`datetime`) < '2016-10-01' AND date(`datetime`) > '2016-08-31' ;
 DELETE FROM `yy_analysis_logs` WHERE date(`datetime`) < '2016-10-01'
备份日志
	 */
    public function logs(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
    	$logtime =date('y_m_d',"$stime");
		$filename= C('LOG_REAL_PATH')."/Analysis/";
		$filearrs = glob($filename."*$logtime.log");
		foreach($filearrs as $filearr){
			$openfile = $this->getArr($filearr);
			foreach($openfile as$k=>$arr){
				if($k%2 !== 0){
					$json = json_decode(substr($arr,6),TRUE);
					if($json['Uuid'] && $json['Major'] && $json['Minor']){
						$wx['datetime'] =$json['time'];
						$wx['uuid'] =$json['Uuid'];
						$wx['major'] =$json['Major'];
						$wx['minor'] =$json['Minor'];
						$wx['pageid'] =$json['pageid'];
						$wx['openid'] =$json['openid'];
						$wx['eid'] =$json['eid'];
						$wx['etype'] =$json['etype'];
						$wx['cid'] =$json['cid'];
						$wx['ctype'] =$json['ctype'];
						$wx['moneys'] =$json['money'];
						$wx['cardnum'] =$json['cardnum'];
						$wx['sn'] =$json['sn'];
						$where = array('datetime'=>$json['time'],'openid'=>$json['openid'],'sn'=>$json['sn']);
						$analysis = $this->analysis_logs_model->where($where)->find();
						\Think\Log::record('logs:'.json_encode($analysis).'wx:'.json_encode($wx));
						if($analysis){
							$this->analysis_logs_model->where($where)->save($wx);
						}else{
							$this->analysis_logs_model->add($wx);
						}
					}
				}
			}
		}
	}

	//url
    function urls(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
    	$logtime =date('y_m_d',"$stime");
		$filename= C('LOG_REAL_PATH')."/Analysis/";
		$filearrs = glob($filename."*$logtime"."url.log");
		if($filearrs){
			foreach($filearrs as $filearr){
				$openfile = $this->getArr($filearr);
				foreach($openfile as$k=>$arr){
					if($k%2 !== 0){
						$json = json_decode(substr($arr,6),TRUE);
						if($json['openid']){
							$wx['datetime'] =$json['time'];
							$wx['openid'] =$json['openid'];
							$wx['eid'] =$json['eid'];
							$wx['etype'] =$json['etype'];
							$wx['cid'] =$json['cid'];
							$wx['ctype'] =$json['ctype'];
							$where = array('datetime'=>$json['time'],'openid'=>$json['openid']);
							$analysis = $this->analysis_urls_model->where($where)->find();
							\Think\Log::record('urls:'.json_encode($analysis).'wx:'.json_encode($wx));
							if($analysis){
								$this->analysis_urls_model->where($where)->save($wx);
							}else{
								$this->analysis_urls_model->add($wx);
							}
						}
					}
				}
			}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
	}
	/*统计中奖, 指定时间*/
	public function timing(){
		$winning = $this->winning(date('y_m_d'));
   	}
	/*统计中奖, 默认昨天*/
	public function winning($logtime = ''){
		if(!$logtime){
      		$logtime =date('y_m_d',strtotime('-1 day'));
		}
		$md = date('md');
		$filename= C('LOG_REAL_PATH')."/Analysis/";
		$filearrs = glob($filename."*$logtime.log");
		foreach($filearrs as $k=>$filearr){
			if(F("WINNING/f$md$k") != $filearr){
				$openfile = $this->getArr($filearr);
				foreach($openfile as $i=>$arr){
					if($i%2 !== 0){
						$cord = $device = $event = $cards = $realuser = $json = $wx = NULL;
						$json = json_decode(substr($arr,6),TRUE);
						if($json['Uuid'] && $json['Major'] && $json['Minor']){
							$device = $this->device_model
							->where(array('uuid'=>$json['Uuid'],'major'=>$json['Major'],'minor'=>$json['Minor'],'status'=>2))
							->order("id DESC")
							->find();
							if($device['store_id']){
								$wx['datetime'] =$json['time'];
								$wx['device_id'] = $device['devid'];
								$store = $this->store_model->where(array('store_id'=>$device['store_id']))->find();
								$wx['bsname'] = $store['title']." - ".$store['title'];
								$wx['bstype'] = $store['stype'];
								$wx['bsaddress'] = $store['address'];
								if(!empty($store['province_id'])){
									$wx['province_id'] = $store['province_id'];
									$wx['city_id'] = $store['city_id'];
									$wx['district_id'] = $store['district_id'];
								}else{
									$wx['province_id'] = 100000;
									$wx['city_id'] = 0;
									$wx['district_id'] = 0;
								}
								$wx['openid'] =$json['openid'];
								$wx['eid'] =$json['eid'];
								$wx['etype'] =$json['etype'];
								$wx['ename'] =$json['ename'];
								$wx['cid'] =$json['cid'];
								$wx['ctype'] =$json['ctype'];
								$wx['cname'] =$json['cname'];
								$wx['moneys'] = $json['money'];
								$wx['cardnum'] = $json['cardnum'];
								$wx['sn'] = $json['sn'];
								$where = array('datetime'=>$json['time'],'device_id'=>$device['devid'],'openid'=>$json['openid']);
								$analysis = $this->analysis_winning_model->where($where)->find();
								\Think\Log::record('winning:'.json_encode($analysis).'wx:'.json_encode($wx));
								if($analysis){
									$this->analysis_winning_model->where($where)->save($wx);
								}else{
									$this->analysis_winning_model->add($wx);
								}
							}
						}
					}
				}
				if($filearr != $filename."$logtime.log"){
					F("WINNING/f$md$k",$filearr);
				}
			}
		}
		//忘记干嘛的了好像没什么卵用的方法。应该是现在这个方法的原始版
//		if(!$logtime){
//			$this->winning_log();
//		}

	}

	public function index(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
    	$wxplsas = Wx::pagelistShakeAroundStatistics($stime);//批量查询页面统计数据

		foreach($wxplsas['data']['pages'] as $plsas){
			$uses = $news = $olds = $user_link = $total_link = $user_pv = $wxpaypeople = $wxpayorder = 0;
			$tsum = $wx = NULL;
			$tsum = $this->analysis_day_model
			->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))
			->find();
			if($tsum){
				$active = $this->analysis_equipment_model->where(array('date(datetime)'=>$time,'click_uv'=>array('egt',5),'pageid'=>array('like',"%".$plsas['page_id']."%")))->count();
				$news = count($this->analysis_users_model->where(array('date(datetime)'=>$time,'date(registered)'=>$time,'pageid'=>$plsas['page_id']))->group('openid')->select());
				$olds = count($this->analysis_users_model->where(array('date(datetime)'=>$time,'date(registered)'=>array('neq',$time),'pageid'=>$plsas['page_id']))->group('openid')->select());
				$user_link = count($this->analysis_urls_model->where(array('date(datetime)'=>$time))->group('openid')->select());
				$total_link = $this->analysis_urls_model->where(array('date(datetime)'=>$time))->count();
				$user_pv = $this->analysis_logs_model->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))->count();
		        $wxpayorder=$this->wxpayorder_model->where(array('date(time)'=>$time))->Sum('total_amount');
		        $wxpaypeople=count($this->wxpayorder_model->where(array('date(time)'=>$time))->group('openid')->select());
				$wx['datetime'] = $time;								//时间
				$wx['pageid'] = $tsum['pageid'];						//页面ID
				$wx['pagename'] = $tsum['name'];						//页面名称
				$wx['shake_uv'] = $tsum['shake_uv'];					//摇周边人
				$wx['shake_pv'] = $tsum['shake_pv'];					//摇周边次
				$wx['click_uv'] = $tsum['click_uv'];					//点击人
				$wx['click_pv'] = $tsum['click_pv'];					//点击次
				$wx['related'] = $tsum['count'];						//关联设备
				$wx['uses'] = $tsum['uses'];							//使用设备
				$uses_average = $tsum['partake']/$tsum['uses'];			//人均设备
				$wx['uses_average'] = round($uses_average,4);
				$wx['active'] = $active;								//活跃设备
				$wx['participate'] = $tsum['partake'];					//参与人数
				if($olds<0){$olds = 0;}
				if($tsum['partake'] == 0){
					$news = 0;
				}
				if($tsum['partake'] < $news){
					$news = 0;
					$olds = $tsum['partake'];
				}
				$wx['olds'] = $olds;									//老用户数
				$olds_ratio = $olds/$tsum['partake']*100;
				$wx['olds_ratio'] = round($olds_ratio,4);				//老用户比

				$wx['news'] = $news;									//新用户数
				$news_ratio = $news/$tsum['partake']*100;
				$wx['news_ratio'] = round($news_ratio,4);				//新用户比
				$wx['winning'] = $tsum['winning'];						//中奖次
				$winning_average = $tsum['winning']/$tsum['partake'];
				$wx['winning_average'] = round($winning_average,4);		//人均中奖
				$wx['nowinning'] = $tsum['nowinning'];					//未中奖次
				$nowinning_average = $tsum['nowinning']/$tsum['partake'];
				$wx['nowinning_average'] = round($nowinning_average,4);	//人均未中奖
				$wx['user_uv'] = $tsum['partake'];						//用户总数
				$wx['user_pv'] = $user_pv;								//用户展示
				$wx['reds'] = $tsum['reds'];							//红包数
				$wx['moneys'] = $tsum['moneys']/100;					//红包金额
				$moneys_average = $tsum['moneys']/$tsum['partake']/100;
				$wx['moneys_average'] = round($moneys_average,4);		//人均成本
				$wx['withdraw'] = $wxpayorder/100;						//提现金额
				$withdraw_average = $wxpayorder/$wxpaypeople/100;
				$wx['withdraw_average'] = round($withdraw_average,4);	//人均提现
				$wx['cards'] = $tsum['cards'];							//卡券
				$wx['reals'] = $tsum['reals'];							//实物
				$wx['total_link'] = $total_link;						//链接次
				$wx['user_link'] = $user_link;							//点击人数
				$analysis = $this->analysis_gather_model->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))->find();
				\Think\Log::record('index:'.json_encode($analysis).'wx:'.json_encode($wx));
				if($analysis){
					$this->analysis_gather_model->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))->save($wx);
				}else{
					$this->analysis_gather_model->add($wx);
				}
			}
		}
   	}
	public function day(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
    	$wxplsas = Wx::pagelistShakeAroundStatistics($stime);//批量查询页面统计数据
    	if(!empty($wxplsas)){
			foreach($wxplsas['data']['pages'] as $plsas){
				$opens = $close = $partake = $uses = $red = $link = $money = $card = $real = $els = $ad = 0;
				$wxssap = $ssar = $pageid = $where = $wx = NULL;
				$pageid[0] =$plsas['page_id'];
		        $wxssap = Wx::searchShakeAroundPage($pageid,0,1);//查询已有的页面
				foreach($wxssap['data']['pages'] as $ssap){
					if($ssap['page_id'] == $plsas['page_id']){
						$name =$ssap['title'].' - '.$ssap['description'];
					}
				}
				if(!$name){
					$name ='页面已被删除';
				}
				$wx['datetime'] =$time;
				$wx['name'] =$name;
				$wx['pageid'] =$plsas['page_id'];
				$wx['shake_uv'] =$plsas['shake_uv'];
				$wx['shake_pv'] =$plsas['shake_pv'];
				$wx['click_uv'] =$plsas['click_uv'];
				$wx['click_pv'] =$plsas['click_pv'];
				$ssar = Wx::searchShakeAroundRelation(null,$plsas['page_id'],0,1);//查询设备与页面的关联关系
				$wx['count'] = $ssar['data']['total_count'];
				$events = $this->event_model
				->field("id,event_status")
				->where(array('wx_page_id'=>$plsas['page_id'],array('date(start_at)'=>array('elt',$time),'_logic'=>"OR",'date(end_at)'=>array('egt',$time))))
				->select();
				if($events){
					foreach($events as $event){
						if($event['event_status'] == 2){
							$opens = $opens+1;
						}
						if($event['event_status'] != 2){
							$close = $close+1;
						}
					}
				}

				$where[0] = array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']);
				if($this->analysis_logs_model->where($where)->find()){
					$partake = count($this->analysis_logs_model->where($where)->group('openid')->select());
					$uses = count($this->analysis_logs_model->where($where)->group('uuid,major,minor')->select());
					$where[1] = array('ctype'=>0);
					$els = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>1);
					$money = $this->analysis_logs_model->where($where)->Sum('moneys');
					$red = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>2);
					$card = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>3);
					$link = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>4);
					$ad = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>5);
					$real = $this->analysis_logs_model->where($where)->count();
				}
				if(!$money){
					$money = 0;
				}
				$wx['uses'] = $uses;
				$wx['open']=$opens;
				$wx['close']=$close;
				$wx['partake'] =$partake;
				$wx['winning'] = $red+$card+$link+$real;
				$wx['nowinning'] = $els+$ad;
				$wx['reds']=$red;
				$wx['moneys']=$money;
				$wx['cards']=$card;
				$wx['reals']=$real;
				$analysis = $this->analysis_day_model
				->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))
				->find();
				\Think\Log::record('day:'.json_encode($analysis).'wx:'.json_encode($wx));
				if($analysis){
					$this->analysis_day_model->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))->save($wx);
				}else{
					$this->analysis_day_model->add($wx);
				}
			}
			return 'success-day_wx数据更新成功';
		}else{
			$this->day_tx();
			return 'error-无需要更新的数据';
		}
	}
	public function day_tx(){
		$analysis = $this->analysis_logs_model->where(array('date(datetime)'=>$time))->group('pageid')->select();
		foreach($analysis as $analysi){
			$opens = $close = $partake = $uses = $red = $link = $money = $card = $real = $els = $ad = 0;
			$where = $wx = NULL;
			$pname= $this->analysis_day_model->where(array('date(datetime)'=>$time,'pageid'=>$analysi['pageid']))->find();
			$wx['datetime'] =$time;
			$wx['name'] =$pname['name'];
			$wx['pageid'] =$analysi['pageid'];
			$wx['shake_uv'] =0;
			$wx['shake_pv'] =0;
			$where[0] = array('date(datetime)'=>$time,'pageid'=>$analysi['pageid']);
			if($this->analysis_logs_model->where($where)->find()){
				$partake = count($this->analysis_logs_model->where($where)->group('openid')->select());
				$uses = count($this->analysis_logs_model->where($where)->group('uuid,major,minor')->select());
				$where[1] = array('ctype'=>0);
				$els = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>1);
				$money = $this->analysis_logs_model->where($where)->Sum('moneys');
				$red = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>2);
				$card = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>3);
				$link = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>4);
				$ad = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>5);
				$real = $this->analysis_logs_model->where($where)->count();
			}

			$events = $this->event_model
			->field("id,event_status")
			->where(array('wx_page_id'=>$plsas['page_id'],array('date(start_at)'=>array('elt',$time),'_logic'=>"OR",'date(end_at)'=>array('egt',$time))))
			->select();
			if($events){
				foreach($events as $event){
					if($event['event_status'] == 2){
						$opens = $opens+1;
					}
					if($event['event_status'] != 2){
						$close = $close+1;
					}
				}
			}
			if(!$money){
				$money = 0;
			}
			$wx['click_uv'] =$partake;
			$wx['click_pv'] =$els+$red+$card+$link+$ad+$real;
			$wx['count'] = 0;
			$wx['uses'] = $uses;
			$wx['open']=$opens;
			$wx['close']=$close;
			$wx['partake'] =$partake;
			$wx['winning'] = $red+$card+$link+$real;
			$wx['nowinning'] = $els+$ad;
			$wx['reds']=$red;
			$wx['moneys']=$money;
			$wx['cards']=$card;
			$wx['reals']=$real;
			$analysis = $this->analysis_day_model
			->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))
			->find();
			\Think\Log::record('day:'.json_encode($analysis).'wx:'.json_encode($wx));
			if($analysis){
				$this->analysis_day_model->where(array('date(datetime)'=>$time,'pageid'=>$plsas['page_id']))->save($wx);
			}else{
				$this->analysis_day_model->add($wx);
			}
		}
			return 'success-day_tx数据更新成功';
	}
	//单活动
    function activity(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
		$etime = strtotime("$time 23:59:59");
		$events = $this->event_model
		->where(array('date(start_at)'=>array('elt',$time),'date(end_at)'=>array('egt',$time)))
		->select();
    	if($events){
    		foreach($events as $event){
				$pageid = $device = $materials= $enter_uv = $enter_pv = $red = $link = $card = $real = $els = $ad = 0;
				$ssar = $where = $wx = NULL;
    			$wx['datetime'] = $time;
    			$wx['name'] = $event['event_name'];
    			$wx['event_id'] = $event['id'];
				$pageid = (int)$event['wx_page_id'];
				$ssar = Wx::searchShakeAroundRelation(null,$pageid);//查询设备与页面的关联关系
				if($ssar){
					$device = $ssar['data']['total_count'];
				}
				$wx['device'] = $device;
				$where[0] = array('date(datetime)'=>$time,'eid'=>$event['id']);
				if($this->analysis_logs_model->where($where)->find()){
					$enter_uv = count($this->analysis_logs_model->where($where)->group('openid')->select());
					$where[1] = array('ctype'=>0);
					$els = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>1);
					$red = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>2);
					$card = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>3);
					$link = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>4);
					$ad = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>5);
					$real = $this->analysis_logs_model->where($where)->count();
					$enter_pv = $els+$red+$card+$link+$ad+$real;
				}else{
					$psas = Wx::pageShakeAroundStatistics($pageid,$stime,$etime);//以页面为维度的数据统计接口
					if($psas){
						$enter_uv = $psas['data'][0]['click_uv'];
						$enter_pv = $psas['data'][0]['click_pv'];
					}
					$cards = explode(',', $event['bind_cards']);
					if(!$cards){$cards = 0;}
					$red = $this->prizes_order_model
					->where(array("card_id"=>array('in',$cards),"event_id"=>$event['id'],'date(winning_time)'=>array('eq',$time)))
					->count();
					if(!$enter_uv || !$enter_pv){
						$enter_uv = $enter_pv = 0;
					}
				}
				$materials = count(explode(',', $event['bind_cards']));
				$wx['pageid'] =	$pageid;
				$wx['enter_uv'] = $enter_uv;
				$wx['enter_pv'] = $enter_pv;
				$wx['materials'] = $materials;
				$wx['winning'] = $red+$card+$link+$real;
				$wx['nowinning'] = $els+$ad;
				$analysis = $this->analysis_activity_model
				->where(array('date(datetime)'=>$time,'event_id'=>$event['id']))
				->find();
				\Think\Log::record('activity:'.json_encode($analysis).'wx:'.json_encode($wx));
				if($analysis){
					$this->analysis_activity_model->where(array('date(datetime)'=>$time,'event_id'=>$event['id']))->save($wx);
				}else{
					$this->analysis_activity_model->add($wx);
				}
    		}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
	}
	//单物料
    function materials(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
		$etime = strtotime("$time 23:59:59");
		$cards = $this->card_model
		->where(array('date(start_at)'=>array('elt',$time),'date(end_at)'=>array('egt',$time)))
		->select();
		if($cards){
			foreach($cards as $cids){
				$display_uv = $display_pv = $red = $card = $link = $real = $els = $ad = 0;
				$logs = $pageid = $where = $wx = NULL;
				$where[0] = array('date(datetime)'=>$time,'cid'=>$cids['id']);
				$logs = $this->analysis_logs_model->where($where)->group('pageid')->select();
				if($logs){
					$display_uv = count($this->analysis_logs_model->where($where)->group('openid')->select());
					foreach($logs as $log){
						$pageid[] = $log['pageid'];
					}
					$where[1] = array('ctype'=>0);
					$els = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>1);
					$red = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>2);
					$card = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>3);
					$link = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>4);
					$ad = $this->analysis_logs_model->where($where)->count();
					$where[1] = array('ctype'=>5);
					$real = $this->analysis_logs_model->where($where)->count();
					$display_pv = $els+$red+$card+$link+$ad+$real;
				}else{
					$events = $this->event_model->where(array("bind_cards"=>array("like","%".$cids['id']."%"),'date(start_at)'=>array('elt',$time),'date(end_at)'=>array('egt',$time)))->select();
					if($events){
						foreach($events as$event){
							$pageids = (int)$event['wx_page_id'];
							$psas = Wx::pageShakeAroundStatistics($pageids,$stime,$etime);//以页面为维度的数据统计接口
							if($psas){
								foreach($psas['data'] as $pdata){
									$display_uv = $display_uv + $pdata['click_uv'];
									$display_pv = $display_pv + $pdata['click_pv'];
								}
								if(!$display_uv || !$display_pv){
									$display_uv = $display_pv = 0;
								}
							}
							$pageid[] = $pageids;
							if(!$cids['id']){$cids['id'] = 0;}
							$card = $this->prizes_order_model
							->where(array("card_id"=>$cids['id'],"event_id"=>$event['id'],'date(winning_time)'=>array('eq',$time)))
							->count();
							$red = $red+$card;
						}
					}
				}
				$pageid = array_merge(array_unique($pageid));
				$wx['datetime'] = $time;
				$wx['name'] = $cids['card_name'];
				$wx['pageid'] =implode(",",$pageid);
				$wx['card_id'] = $cids['id'];
				$wx['card_type'] = $cids['card_type'];
				$wx['display_uv'] = $display_uv;
				$wx['display_pv'] = $display_pv;
				$wx['winning'] = $red+$card+$link+$real;
				$wx['nowinning'] = $els+$ad;
				$wx['moneys'] = $cids['card_count'];
				$analysis = $this->analysis_materials_model
				->where(array('date(datetime)'=>$time,'card_id'=>$cids['id']))
				->find();
				\Think\Log::record('materials:'.json_encode($analysis).'wx:'.json_encode($wx));
				if($analysis){
					$this->analysis_materials_model->where(array('date(datetime)'=>$time,'card_id'=>$cids['id']))->save($wx);
				}else{
					$this->analysis_materials_model->add($wx);
				}
			}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
	}
	//单设备
    function equipment(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$stime = strtotime("$time 00:00:00");
		$dlsas = Wx::devicelistShakeAroundStatistics($stime);
		$p = ceil($dlsas['total_count']/50);
		if($p){
		for($i=1;$i<=$p;$i++){
			$wxdlsas = NULL;
			$wxdlsas = Wx::devicelistShakeAroundStatistics($stime,$i);
			if($wxdlsas){
				foreach($wxdlsas['data']['devices'] as $wxdlas){
					$wxssars = $pageid = NULL;
					$wxssars = Wx::searchShakeAroundRelation($wxdlas['device_id'],NULL);
					if($wxssars){
						foreach($wxssars['data']['relations'] as $wxssar){
							$pageid[] = $wxssar['page_id'];
						}
						$pageid = array_merge(array_unique($pageid));
						$wx['pageid'] =implode(",",$pageid);
					}else{
						$wx['pageid'] ='';
					}
					$wx['datetime'] =$time;
					$wx['device_id'] =$wxdlas['device_id'];
					$wx['activitys'] =0;
					$wx['click_pv'] = $wxdlas['click_pv'];
					$wx['click_uv'] = $wxdlas['click_uv'];
					$wx['winning'] = 0;
					$wx['nowinning'] = 0;
					$wx['reds'] = 0;
					$wx['moneys'] = 0;
					$wx['cards'] = 0;
					$wx['reals'] = 0;
					$wx['bsname'] = '未绑定店铺信息';
					$wx['bstype'] = 500;
					$wx['bsaddress'] =  '未绑定店铺信息';
					$wx['partner'] =  '-';
					$wx['mobile'] =  0;
					$wx['province_id'] = 100000;
					$wx['city_id'] = 0;
					$wx['district_id'] = 0;
					$analysis = $this->analysis_equipment_model
					->where(array('date(datetime)'=>$time,'device_id'=>$wxdlas['device_id']))
					->find();
					\Think\Log::record('equipment:'.json_encode($analysis).'wx:'.json_encode($wx));
					if($analysis){
						$this->analysis_equipment_model->where(array('date(datetime)'=>$time,'device_id'=>$wxdlas['device_id']))->save($wx);
					}else{
						$this->analysis_equipment_model->add($wx);
					}
				}
			}
		}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
	}
	//更新设备
    function update_equipment(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$analysis = $this->analysis_equipment_model->where(array('date(datetime)'=>$time))->select();
		if($analysis){
			foreach($analysis as $analysi){
				$where = $wxssars = $pageid = $wx = NULL;
				$events = $click_pv = $click_uv = $els = $red = $card = $link = $ad = $real = $money = 0;
				$device = $this->device_model->where(array('devid'=>$analysi['device_id']))->order("id DESC")->find();
				if($device){
					if(!$device['uuid'] || !$device['minor'] || !$device['major']){
						$data = array("device_identifiers" => array(array("device_id" => $analysi['device_id'])));
	                    $dev = Wx::searchShakeAroundDevice($data);
						$device['uuid'] = $dev['data']['devices'][0]['uuid'];
						$device['minor'] = $dev['data']['devices'][0]['minor'];
						$device['major'] = $dev['data']['devices'][0]['major'];
						$this->device_model->where(array('devid'=>$analysi['device_id']))->save($device);
					}
					$where[0] = array('date(datetime)'=>$time,'uuid'=>$device['uuid'],'minor'=>$device['minor'],'major'=>$device['major']);
					$logs = $this->analysis_logs_model->where($where)->group('pageid')->select();
					if($logs){
						$click_uv = count($this->analysis_logs_model->where($where)->group('openid')->select());
						foreach($logs as $log){
							$pageid[] = $log['pageid'];
						}
						$where[1] = array('ctype'=>0);
						$els = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>1);
						$money = $this->analysis_logs_model->where($where)->Sum('moneys');
						$red = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>2);
						$card = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>3);
						$link = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>4);
						$ad = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>5);
						$real = $this->analysis_logs_model->where($where)->count();
						$click_pv = $els+$red+$card+$link+$ad+$real;
						$wx['click_pv'] = $click_pv;
						$wx['click_uv'] = $click_uv;
						$wx['winning'] = $red+$card+$link+$real;
						$wx['nowinning'] = $els+$ad;
						$wx['reds'] = $red;
						$wx['cards'] = $card;
						$wx['reals'] = $real;
						if($money){
							$wx['moneys'] = $money;
						}
					}
					$pageid = array_merge(array_unique($pageid));
					if($pageid){
						$events =$this->event_model
						->where(array('wx_page_id'=>array('in',$pageid),
								array('date(start_at)'=>array('elt',$time),'date(end_at)'=>array('egt',$time))
								))
						->count();
						$wx['pageid'] =implode(",",$pageid);
						$wx['activitys'] =$events;
					}

						$store = $this->store_model->where(array('store_id'=>$device['store_id']))->find();
						$wx['bsname'] = $store['title']." - ".$store['title'];
						$wx['bstype'] = $store['stype'];
						$wx['bsaddress'] = $store['address'];

					if(!empty($store['province_id'])){
						$wx['province_id'] = $store['province_id'];
						$wx['city_id'] = $store['city_id'];
						$wx['district_id'] = $store['district_id'];
					}
					$this->analysis_equipment_model->where(array('date(datetime)'=>$time,'device_id'=>$analysi['device_id']))->save($wx);
				}
			}
			return 'success-数据更新成功';
		}else{
			$logs = $this->analysis_logs_model->where(array('date(datetime)'=>$time))->group('uuid,major,minor')->select();
			if($logs){
				foreach($logs as $log){
					$where = $wdevice = $wx = NULL;
					$events = $click_pv = $click_uv = $els = $red = $card = $link = $ad = $real = $money = 0;
					$wdevice['uuid'] = $log['uuid'];
					$wdevice['minor'] = $log['minor'];
					$wdevice['major'] = $log['major'];
					$wdevice['status'] = 2;
					$device = $this->device_model->where($wdevice)->order("id DESC")->find();
					if($device['store_id']){
						$events =$this->event_model
						->where(array('wx_page_id'=>$log['pageid'],array('date(start_at)'=>array('elt',$time),'date(end_at)'=>array('egt',$time))))
						->count();
						$wx['pageid'] =$log['pageid'];
						$wx['activitys'] =$events;
						$wx['datetime'] =$time;
						$wx['device_id'] =$device['devid'];
						$store = $this->store_model->where(array('store_id'=>$device['store_id']))->find();
						$wx['bsname'] = $store['title']." - ".$store['title'];
						$wx['bstype'] = $store['stype'];
						$wx['bsaddress'] = $store['address'];

						if(!empty($store['province_id'])){
							$wx['province_id'] = $store['province_id'];
							$wx['city_id'] = $store['city_id'];
							$wx['district_id'] = $store['district_id'];
						}else{
							$wx['province_id'] = 100000;
							$wx['city_id'] = 0;
							$wx['district_id'] = 0;
						}
						$where[0] = array('date(datetime)'=>$time,'uuid'=>$log['uuid'],'minor'=>$log['minor'],'major'=>$log['major']);
						$click_uv = count($this->analysis_logs_model->where($where)->group('openid')->select());
						$where[1] = array('ctype'=>0);
						$els = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>1);
						$money = $this->analysis_logs_model->where($where)->Sum('moneys');
						$red = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>2);
						$card = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>3);
						$link = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>4);
						$ad = $this->analysis_logs_model->where($where)->count();
						$where[1] = array('ctype'=>5);
						$real = $this->analysis_logs_model->where($where)->count();
						$click_pv = $els+$red+$card+$link+$ad+$real;
						$wx['click_pv'] = $click_pv;
						$wx['click_uv'] = $click_uv;
						$wx['winning'] = $red+$card+$link+$real;
						$wx['nowinning'] = $els+$ad;
						$wx['reds'] = $red;
						$wx['cards'] = $card;
						$wx['reals'] = $real;
						if($money){
							$wx['moneys'] = $money;
						}
						$analysis = $this->analysis_equipment_model
						->where(array('date(datetime)'=>$time,'device_id'=>$device['devid']))
						->find();
						\Think\Log::record('equipment:'.json_encode($analysis).'wx:'.json_encode($wx));
						if($analysis){
							$this->analysis_equipment_model->where(array('date(datetime)'=>$time,'device_id'=>$device['devid']))->save($wx);
						}else{
							$this->analysis_equipment_model->add($wx);
						}
					}
				}
				return 'success-数据更新成功';
			}else{
				return 'error-无需要更新的数据';
			}
		}
	}


	//单用户
    function users(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$userslists = $this->analysis_logs_model->where(array('date(datetime)'=>$time))->group('openid')->select();
		if($userslists){
			foreach($userslists as $userslist){
				$realuser = $wx = NULL;
				$realuser = $this->real_users_model->where(array('weixin_id'=>$userslist['openid']))->find();
				$wx['datetime'] = $time;
				if(!empty($realuser['weixin_id'])){
					$wx['openid'] = $realuser['weixin_id'];
					$wx['nickname'] = $realuser['nickname'];
					$wx['registered'] = $realuser['created_at'];
					$wx['enter'] = $realuser['last_login'];
				}else{
					$wx['openid'] = '-';
					$wx['nickname'] = '此用户不存在';
					$wx['registered'] = '0000-00-00 00:00:00';
					$wx['enter'] =  '0000-00-00 00:00:00';
				}
				$wx['pageid'] = $userslist['pageid'];
				$wx['winning'] = 0;
				$wx['reds'] = 0;
				$wx['moneys'] = 0;
				$wx['cards'] = 0;
				$wx['reals'] = 0;
				$wx['shakes'] = 0;
				$analysis = $this->analysis_users_model
				->where(array('date(datetime)'=>$time,'openid'=>$userslist['openid']))
				->find();
				\Think\Log::record('users:'.json_encode($analysis).'wx:'.json_encode($wx));
				if($analysis){
					$this->analysis_users_model->where(array('date(datetime)'=>$time,'openid'=>$userslist['openid']))->save($wx);
				}else{
					$this->analysis_users_model->add($wx);
				}
			}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
	}
    function update_users(){
		$time = date('Y-m-d',strtotime('-1 day'));
		$analysis = $this->analysis_users_model->where(array('date(datetime)'=>$time))->select();
		if($analysis){
			foreach($analysis as $analysi){
				$els = $red = $card = $link = $real = $money = 0;
				$where = $wx = NULL;
				$where[0] = array('openid'=>$analysi['openid'],'date(datetime)'=>$time);
				$where[1] = array('ctype'=>0);
				$els = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>1);
				$money = $this->analysis_logs_model->where($where)->Sum('moneys');
				$red = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>2);
				$card = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>3);
				$link = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>4);
				$ad = $this->analysis_logs_model->where($where)->count();
				$where[1] = array('ctype'=>5);
				$real = $this->analysis_logs_model->where($where)->count();
				$shakes = $els+$red+$card+$link+$ad+$real;

				$wx['winning'] = $red+$card+$link+$real;
				$wx['reds'] = $red;
				if($money){
					$wx['moneys'] = $money;
				}
				$wx['cards'] = $card;
				$wx['reals'] = $real;
				$wx['shakes'] = $shakes;
				$this->analysis_users_model->where(array('date(datetime)'=>$time,'openid'=>$analysi['openid']))->save($wx);
			}
			return 'success-数据更新成功';
		}else{
			return 'error-无需要更新的数据';
		}
    }
}
